<template>
  <div>
    <div>分配权限功能</div>
    <el-tree
      ref="tree"
      default-expand-all
      show-checkbox
      check-strictly
      node-key="id"
      :data="treeData"
      :props="{'label':'name'}"
    />
    <el-row class="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" @click="cancelButton">取 消</el-button>
        <el-button size="small" type="primary" @click="setRolesBtn">确 定</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permission'
import { getRoleId, assignPerm } from '@/api/setting'
import { tranListToTreeData } from '@/utils'
export default {
  name: 'AssignPermission',
  props: {
    roleId: {
      type: [Number, String],
      required: true
    }
  },
  data() {
    return {
      treeData: [] // 树形 权限列表数据
    }
  },
  created() {
    // 调用 获取权限列表的方法
    this.getPermissionList()
    // 调用 获取权限列表的方法
    this.getRoleId()
  },
  methods: {
    // 获取权限列表
    async getPermissionList() {
      const res = await getPermissionList()
      this.treeData = tranListToTreeData(res.data, '0')
    },
    // 获取权限列表 通过ID
    async getRoleId() {
      const res = await getRoleId(this.roleId)
      this.$refs.tree.setCheckedKeys(res.data.permIds)
    },

    // 确定 设置权限按钮
    async setRolesBtn() {
      // 获取选中项的 ID
      const permIds = this.$refs.tree.getCheckedKeys()
      // 调用 API，给角色设置权限
      const res = await assignPerm({ id: this.roleId, permIds })
      this.$message.success(res.message)
      this.$emit('close')
      // 重新获取权限列表
      this.getPermissionList()
    },

    // 取消
    cancelButton() {
      this.$emit('close')
    }
  }
}
</script>

<style lang="scss" scoped>
  .footer{
    margin-top: 30px;
  }
</style>>

